# -*- coding: utf-8 -*-
"""
===============================
@Author     : Zuo WenTao
@Time       : 2024/6/27 14:37
@Description:
@Change     :
@File       : DownLoaderTool.py.py
===============================
"""
import re
import time

import fitz
import os

from loguru import logger

from utils.Request2 import Request2


class DownLoaderTool:
    def __init__(self):
        pass

    def universal_download(self, pdf_url, file_path, headers=None, proxy=None, method=None):
        """
        :param pdf_url:  PDF下載地址
        :param file_path: 下載保存地址
        :param headers: 头部信息
        :param proxy: 代理
        :param: method: 请求方式： POST OR GET
        :return:
        """
        file_list = ["pdf", "caj", "txt", "epub", "octet-stream"]
        try:
            if not method:
                response = Request2.GetResponse(pdf_url, stream=True, Headers=headers, Proxy=proxy)
            elif method in ["POST", "GET"]:
                response = Request2.GetResponse(pdf_url, stream=True, Headers=headers, Proxy=proxy, method=method)
            else:
                raise ValueError("不支持的请求模式，请求方式为：POST OR GET")
            content_type = response.headers.get("content-type", "")
            content_disposition = response.headers.get("content-disposition", "")
            if [x for x in file_list if x in content_type] or "pdf" in [x for x in file_list if x in content_disposition]:
                st = int(time.time())
                if not os.path.exists(os.path.split(file_path)[0]):
                    os.makedirs(os.path.split(file_path)[0])
                with open(file_path, "wb+") as fout:
                    for c in response.iter_content(chunk_size=1024):
                        et = int(time.time())
                        if et - st >= 60:
                            logger.error("下载超时！")
                            response.close()
                            raise
                        fout.write(c)
                    fout.close()
                response.close()
                if ".pdf" in file_path and not self.verify_pdf(file_path):
                    logger.error("pdf 检查没有通过！")
                    self.delete_file(file_path)
                    return False, "检查PDF内容不正确"
                return True, "Format正确"
            else:
                logger.error(f"{pdf_url}下载文件格式不正确:{content_type}！")
                return False, "Format不正确"
        except Exception as e:
            logger.error(f"下载失败！ 失败原因：{e}")
            return False, ""

    def verify_pdf(self, file_path):
        try:
            Doc = fitz.open(file_path)
            page = Doc.page_count
            if not page:
                return False
            return True
        except:
            return False

    def delete_file(self, file_path):
        try:
            os.remove(file_path)
            return True
        except Exception as e:
            return False

    @staticmethod
    def is_html_complex(text):
        """
        使用正则表达式判断字符串是否是HTML
        :param text: 要判断的字符串
        :return: 如果是HTML，返回True；否则返回False
        """
        html_pattern = re.compile(r'<!DOCTYPE html>|<html[^>]*>|<body[^>]*>|<head[^>]*>|<title[^>]*>|<div[^>]*>|<span[^>]*>|<a[^>]*>|<img[^>]*>|<h[1-6][^>]*>|<p[^>]*>', re.IGNORECASE)
        return bool(html_pattern.search(text))
